/*
 * @Date: 2021-08-14 16:05:33
 * @information: app
 */
const Koa = require('koa')
const bodyParser = require('koa-bodyparser')
const cors = require('koa2-cors')
const error = require('koa-json-error')
import router from './router/SwaggerRouter'
const globalRes = require('./utils/globalRes')
const responseHandle = require('./middleware/ResponseHandle')
// const config = require('../config/index')


const app = new Koa()

const initApp = () => {
  app.use(async (ctx, next) => {
    console.log(`Process ${ctx.request.method} ${ctx.request.url}...`)
    await next()
  })
  // 允许跨域
  app.use(cors())
  // 处理body中的参数
  app.use(bodyParser())
  // 错误处理中间件
  app.use(error({
    postFormat: (e, { stack, message, name, status }) => {
      return globalRes.failRes(`${message}: ${stack}`, status)
    }
  }))
  // 返回格式
  app.use(responseHandle.success())
  // 启动路由
  app.use(router.routes())
  // 这是官方文档的推荐用法,在当所有路由中间件最后调用.此时根据ctx.status设置response响应头
  app.use(router.allowedMethods())
  // 启动服务
  const port = 8888
  app.listen(port, () => {
    console.log(`服务已启动：http://localhost:${port}`)
  })
}

initApp()
